<template>
  <div>
    <el-calendar ref="calendar">
      <template #header="{ date }">
        <div>{{ date }}</div>
        <el-button-group>
          <el-button size="small" @click="selectDate('prev-month')">上个月</el-button>
          <el-button size="small" @click="selectDate('today')">当天</el-button>
          <el-button size="small" @click="selectDate('next-month')">下个月</el-button>
        </el-button-group>
      </template>
      <template #date-cell="{ data }">
        <p :class="data.isSelected ? 'is-selected' : ''">
          {{ data.day.split("-").slice(1).join("-") }}
          {{ data.isSelected ? "✔️" : "" }}
        </p>
        <div>
          <el-button type="primary" text @click="viewDate(data)">查看</el-button>
          <el-button type="primary" text @click="confirmDate(data)" v-if="data.day >= currentDay">新增</el-button>
        </div>
      </template>
    </el-calendar>
    <el-dialog v-model="dialogEditVisible" title="排课计划" width="800">
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="教练" prop="coachId">
          <el-select-v2
            v-model="ruleForm.coachId"
            :props="props"
            placeholder="请选择教练"
            :options="coachesOptions"
            @change="coachChange"
          />
        </el-form-item>
        <el-form-item label="课程" prop="courseId">
          <el-select-v2
            v-model="ruleForm.courseId"
            :props="props"
            placeholder="请选择课程"
            :options="courseOptions"
            @change="courseChange"
          />
        </el-form-item>
        <el-form-item label="上课时间" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择">
            <el-option label="上午（10:00 - 11:00）" value="上午" />
            <el-option label="下午（14:00 - 15:00）" value="下午" />
            <el-option label="晚上（19:00 - 20:00）" value="晚上" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog v-model="dialogViewVisible" title="当日排课信息" width="800">
      <el-table :data="tableData" v-loading="loading" height="500">
        <el-table-column type="index" width="80" label="序号" />
        <el-table-column property="coachName" label="课程名称" width="150" />
        <el-table-column property="courseName" label="教练名称" width="200" />
        <el-table-column property="time" label="上课日期" />
        <el-table-column property="type" label="上课时间" />
      </el-table>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from "vue"
import { CalendarDateType, CalendarInstance, FormInstance, FormRules, ElMessage } from "element-plus"
import { getCoachesListDataApi, getCoachCourseListDataApi, addCoachCourseListDataApi } from "@/api/coaches"
import { getCourseListDataApi } from "@/api/course"
import { type GetCoachesData, type COUCoachCourseRequestData } from "@/api/coaches/types/coaches"
import { type GetCourseData } from "@/api/course/types/course"
import { usePagination } from "@/hooks/usePagination"
import { formatDateTime } from "@/utils/index"
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const formSize = ref<any>("default")
const props = {
  label: "name",
  value: "id"
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<COUCoachCourseRequestData>({
  avatar: "",
  coachId: null,
  coachName: "",
  courseId: null,
  courseName: "",
  type: "上午",
  desc: "",
  id: null,
  image: "",
  time: "",
  typeId: undefined,
  typeName: ""
})
const currentDay = formatDateTime(new Date())
const dialogEditVisible = ref(false)
const dialogViewVisible = ref(false)
const calendar = ref<CalendarInstance>()
const rules = reactive<FormRules<GetCoachesData>>({})
const coachesOptions = ref<GetCoachesData[]>([])
const courseOptions = ref<GetCourseData[]>([])
const search = reactive({
  time: ""
})
const viewDate = (e: any) => {
  search.time = e.day
  getTableData()
}
const loading = ref<boolean>(false)
const tableData = ref<GetCoachesData[]>([])
const getTableData = () => {
  loading.value = true
  getCoachCourseListDataApi({
    pageNum: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    time: search.time
  })
    .then(({ data }) => {
      paginationData.total = data.total
      tableData.value = data.rows
      dialogViewVisible.value = true
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData)
const selectDate = (val: CalendarDateType) => {
  if (!calendar.value) return
  calendar.value.selectDate(val)
}
const confirmDate = async (e: any) => {
  console.log(e)
  const coachesData = await getCoachesListDataApi()
  coachesOptions.value = coachesData.data
  const courseData = await getCourseListDataApi()
  courseOptions.value = courseData.data
  dialogEditVisible.value = true
  ruleForm.time = e.day
}
const coachChange = (e: any) => {
  const ret = coachesOptions.value.find((res) => res.id == e)
  if (ret) {
    ruleForm.coachName = ret.name
    ruleForm.avatar = ret.avatar
  }
}
const courseChange = (e: any) => {
  const ret = courseOptions.value.find((res) => res.id == e)
  if (ret) {
    ruleForm.courseName = ret.name
    ruleForm.desc = ret.desc
    ruleForm.image = ret.image
    ruleForm.typeName = ret.typeName
    ruleForm.typeId = ret.typeId
  }
}
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      addCoachCourseListDataApi(ruleForm).then(() => {
        ElMessage.success("新增成功")
        dialogEditVisible.value = false
      })
      console.log("submit!")
    } else {
      console.log("error submit!", fields)
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
<style scoped lang="scss">
.is-selected {
  color: #1989fa;
}
.pager-wrapper {
  margin: 20px 0;
}
</style>
<style>
.el-calendar-table .el-calendar-day {
  height: 100px;
}
</style>
